
const {EquipmentLogModel,EquipmentModel } = require('../../models/index')
const koaTool = require('../../commons/koa_tool')
const _const = require('../../commons/const')
class EquipmentLogController {

    //列表
    list = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['page'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            page,
            limit,
            equipment_code,
        } = ctx.request.query;


        limit = Number(limit)
        page = page || 0
        page = page - 1
        let query = {
            status: 1,
            // 针对数据量大的问题，只取3天的日志数据
            create_at: {"$gt": Date.now() - (3 * 24 * 60 * 60 * 1000)}
        };


        if (equipment_code) {
            const reg = new RegExp(equipment_code, 'i') //不区分大小写
            query.$and = query.$and || []
            query.$and.push({
                $or: [
                    {'equipment_code': {$regex: reg}},
                ]
            })
        }

        ["num_status"].forEach(prop => {
            if(ctx.request.query[prop]){
                query[prop] = ctx.request.query[prop]
            }
        })
        // 根据数据权限过滤
        let enterpriseId = ctx.state._user.enterprise_id;
        if(enterpriseId){
            query.enterprise_id = enterpriseId
        }
        let total = await EquipmentLogModel.countDocuments(query)
        let list = await EquipmentLogModel.find(query,"equipment_code num_status real_num create_at").sort([
            ['create_at',-1],
        ]).skip(page * limit).limit(limit).lean();
        // console.log("page log item", list[0].create_at)
        list = list.map(item => {
            item.numStatusName = _const.NUM_STATUS_MAP[item.num_status]
            return item;
        })
        koaTool.succ(ctx, {
            list,
            total
        })
    }
    // 根据企业ID和柜子的ID获取对应所有设备下前50条数据
    getAllEquLogDataByEnterId = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, []);

        let enterpriseId = input.enterpriseId;
        if(!enterpriseId) return koaTool.error(ctx,"企业Id不存在");
        
        let equDataList = await EquipmentModel.find({enterprise_id: enterpriseId, status: 1, machine_status: 1}).lean();
        if(equDataList && equDataList.length == 0){
            return koaTool.error(ctx,"该账号下无正常设备数据,请检查");
        }

        let resultData = {};
        for(let i = 0; i < equDataList.length; i++){
            let item = equDataList[i];
            let queryData = {
                enterprise_id: item.enterprise_id,
                equipment_id: item._id,
                equipment_code: item.code,
                real_num: {$lt: 6000}
            }
            let logData = await EquipmentLogModel.find(queryData, "real_num create_at -_id").sort([
                ['create_at',-1],
            ]).limit(50).lean();
            resultData[item.code] = {
                type: item.type,
                logData: logData
            }
        }
    
        koaTool.succ(ctx, resultData)

    }
     // 根据企业ID和柜子的ID获取对应设备下前n条数据
    getEquLogDataByEnterId = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, []);
        let {enterpriseId, equipmentId, isNoFirst} = input;
        if(!(enterpriseId && equipmentId)) return koaTool.error(ctx,"请求参数缺失");
        
       
        // let equipmentData = await EquipmentModel.findById(equipmentId).lean();
        // if(equipmentData && equipmentData.machine_status != 1){
        //     return koaTool.error(ctx,"设备异常，请检查");
        // }

        let queryData = {
            enterprise_id: enterpriseId,
            equipment_id: equipmentId,
            real_num: {$lt: 6000}
        }

        // 可视化数据的首次请求数量取大数  二次请求数量取小值  300  ~ 10
        // 判断是否首次渲染数据，若首次则直接取300条数据，后续的更新，以前十条的数据进行更新迭代
        let limit = isNoFirst == "true" ? 10 : 50
        let logDataList = await EquipmentLogModel.find(queryData, "real_num -_id create_at").sort({_id: -1}).skip(0).limit(limit).lean();
        // logDataList.forEach(item => )
        

        koaTool.succ(ctx, logDataList)

    }

    // 根据企业Id 获取异常数据
    getWarnEquLogDataByEnterId = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, []);
        let {enterpriseId} = input;
        if(!enterpriseId) return koaTool.error(ctx,"请求参数缺失");
        
       

        let queryData = {
            enterprise_id: enterpriseId,
            num_status: 2,
            real_num: {$lt: 6000}
        }

        let logDataList = await EquipmentLogModel.find(queryData, "equipment_id cabinet_id equipment_code real_num create_at -_id")
                                            .populate({path: "equipment_id", select: "name"})
                                            .populate({path: "cabinet_id", select: "name"})
                                            .sort([['create_at',-1]]).limit(10).lean();
        let resultData  = logDataList.map(item => {
            return {
                cabinetName: item.cabinet_id.name,
                equipmentName: item.equipment_id.name,
                equipmentCode: item.equipment_code,
                realNum: item.real_num,
                warningDate: item.create_at
            }
        })

        koaTool.succ(ctx, resultData)

    }

    // 数据状态
    getNumStatusList = async (ctx) => {
        const {NUM_STATUS_LIST} = require('../../commons/const.js');
        return koaTool.success(ctx,"获取成功",{
            list: NUM_STATUS_LIST
        })
    }

 

}

module.exports=new EquipmentLogController()

